package com.prince.web.base;

import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.UUID;

import com.prince.web.service.ConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.prince.constant.Constants;

import javax.annotation.Resource;

@Service
public abstract class BaseService {

	protected   Logger logger = LoggerFactory.getLogger(BaseService.class);
	//windows 路径
	@Value("${windows_upload_image_path}")
	private String windows_upload_image_path;
	//linux 路径
	@Value("${linux_upload_image_path}")
	private String linux_upload_image_path;
	@Resource
	private ConfigService configService;
	/**
	 * 上传照片
	 * @param multFile
	 * @return
	 */
	public String uploadImage(MultipartFile multFile) {
		// 获取windows环境还是其他环境
		Properties properties = System.getProperties();
		String os = properties.getProperty("os.name");
		logger.info("当前运行环境 ：" + os);
		// 每次只会传一个照片
		String filename = multFile.getOriginalFilename();

		// 获取后缀名
		//防止重名
		String type = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
		filename = UUID.randomUUID().toString().replace("-", "") + "." + type;
		String path = null;
		// 根据不同的运行环境上传图片地址不同
		if (os.contains("Windows")) {
			path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
			path = path.substring(0, path.indexOf("parent") + 7) + this.windows_upload_image_path;
			logger.info("windows环境上传图片路径：" + path);
		} else {
			path = this.linux_upload_image_path;
			logger.info("其它环境上传图片路径 ： " + path);
		}

		// 文件保存路径
		File file = new File(path);
		// 文件夹是否存在 不存在递归创建
		if (!file.isDirectory()) {
			file.mkdirs();
		}
		try {
			logger.info("上传图片地址：" + file + "/"+ filename);
			multFile.transferTo(new File(file  + "/"+ filename));
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		String appDomain = configService.findConfigName(Constants.imgDomain).getValue();
		//域名+ /upload + /名称
		return appDomain + Constants.IMAGE_ADDR + "/" + filename;
	}
	
	/**
	 * 获取系统路径
	 * @return
	 */
	public String findSystemPath() {
		Properties properties = System.getProperties();
		String os = properties.getProperty("os.name");
		if (os.contains("Windows")) {
			logger.info("windows环境上传图片路径：" + this.linux_upload_image_path);
			return this.windows_upload_image_path;
		} else {
			logger.info("其它环境上传图片路径 ： " + this.linux_upload_image_path);
			return this.linux_upload_image_path;
		}
	}

}
